package redis.inaction.spring.ops;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.inaction.spring.dao.CityDao;
import redis.inaction.spring.entity.City;

import java.time.Duration;

@Slf4j
public class RedisTemplateOps {

    @Autowired
    private RedisTemplate<String, City> redisTemplate;

    @Autowired
    private CityDao cityDao;

    public City getCity(String code){
        log.info("RedisTemplate ops..");
        City city = redisTemplate.opsForValue().get(code);
        if(City.CITY_NULL.equals(city)){
            //直接返回不回源数据库查询
            return null;
        }
        if(city == null){
            city = cityDao.getCity(code);
            City cacheCity = city == null ? City.CITY_NULL : city;
            redisTemplate.opsForValue().set(cacheCity.getCode(), cacheCity, Duration.ofMinutes(1));
        }
        return city;
    }

}
